#!/usr/bin/python
#-*- coding:utf-8 –*-
import platform as p
import os
import re
#p1 = p.system()
path = "/private/etc"
os.chdir(path)
file = 'hosts'
def read_hosts():
    with open(file, mode='r') as fs:
        data = fs.readlines()
        fs.close()
    return data

def GetHosts():
    datas = read_hosts()
    l=[]
    for data in datas:
        regular=re.match('#', data)
        if regular != None:
            continue
        l.append(data)
    return l
def write_host(hostvalue):
    with open(file, mode='a') as f:
        f.write("\n")
        f.write(hostvalue)
        f.close()
    """
    替换文件中的字符串
    :param file:文件名
    :param old_str:旧字符串
    :param new_str:新字符串
    :return:
    """
def alter(old_str,new_str):
    file_data = ""
    with open(file, mode='r') as f:
        for line in f:
            if old_str in line:
                line = line.replace(old_str,new_str)
            file_data += line
    with open(file,mode='w') as f:
        f.write(file_data)
        f.close()

def copyFile(vlaue):
    old_File = file
    old_f = open(old_File, mode='r')  # 打开需要备份的文件
    content = old_f.read()  # 将文件内容读取出来
    old_f.close()
    path = "/private/etc/copyhost"
    if os.path.exists(path):
       pass
    else:
       os.mkdir(path)
    p1 = p.system()
    os.chdir(path)
    # 构建新的文件名.加上备份的后缀
    new_file = vlaue
    new_f = open(new_file, mode='w')  # 以写的模式去打开新文件,不存在则创建
    new_f.write(content)  # 将读取的内容写到备份文件中
    new_f.close()
    pass
def backcopy(vlaue):
    new_f = open(file, mode='w')  # 以写的模式去打开新文件,不存在则创建
    path = "/private/etc/copyhost"
    os.chdir(path)
    old_File = vlaue
    old_f = open(old_File, mode='r')  # 打开需要备份的文件
    content = old_f.read()  # 将文件内容读取出来
    old_f.close()
    new_f.write(content)  # 将读取的内容写到备份文件中
    new_f.close()
    pass
if __name__ == '__main__':
  colours = ["所有host","添加host","修改host","删除host","备份host","还原host"]
  for i in range(0, len(colours)):
    print str(i)+":",colours[i]
  print "请输入选项:"
  str = input()
  if str == 0 :
     host_list=GetHosts()
     for v in host_list:
        print v
  elif str == 1:
     print "请输入Hosts-例如127.0.0.1 xx.com:"
     #Python3.X这里改为input()
     vlaue = raw_input()
     write_host(vlaue)
  elif str == 2:
    host_list=GetHosts()
    for v in host_list:
        print v
    print "请输入原内容"
    vlaue = raw_input()
    print "请输入要修改的内容"
    vlaue2 = raw_input()
    alter(vlaue,vlaue2)
    print "修改成功"
  elif str == 3:
    host_list=GetHosts()
    for v in host_list:
        print v
    print "请输入要删除的内容"
    vlaue = raw_input()
    alter(vlaue,"#"+vlaue)
    print ("删除成功")
  elif str == 4:
    print "请输入备份文件名"
    vlaue = raw_input()
    copyFile(vlaue)
    print ("备份成功,文件在/private/etc/copyhost目录下")
  elif str == 5:
    path = "/private/etc/copyhost"
    file_name_list = os.listdir(path)
    for v in file_name_list:
        print v
    print ("请输入要恢复的文件名")
    vlaue = raw_input()
    backcopy(vlaue)
    print ("恢复完成")
  else :
    print ("输入错误")